//
// Created by 30938 on 2022/8/26.
//

#include "IniParse.h"

string IniParse::strip(const string &str) {
    int start = str.find_first_not_of(" \n\t");
    int end = str.find_last_not_of(" \n\t");
    if (start == string::npos || end == string::npos) {
        return "";
    }
    string str2 = str.substr(start, end - start + 1);
    return str2;
}

IniParse::IniParse(const string &path) {
    FILE *fp = fopen(path.c_str(), "r");
    if (fp == nullptr) {
        throw "not flie";
    }
    string section;
    int linenum = 0;
    while (!feof(fp)) {
        ++linenum;
        char buffer[256] = {0};
        fgets(buffer, sizeof(buffer), fp);
        string line = strip(buffer);
        if (line.front() == '#' || line.empty()) {
            continue;
        }
        int index = line.find('=');
        if (line.front() == '[' && line.back() == ']') {
            section = line.substr(1, line.size() - 2);
            unordered_map<string, string> _map;
            data[section] = _map;
        } else if (index != string::npos) {
            string key = strip(line.substr(0, index));
            string val = strip(line.substr(index + 1));
            data[section].insert({key,val});
        } else {
            char errorMsg[32] = {0};
            sprintf(errorMsg, "file %d line error", linenum);
            throw errorMsg;
        }
    }
    fclose(fp);
}

unordered_map<string, string> IniParse::getSection(const string &section) {
    return data.at(section);
}

string IniParse::grtValue(const string &section, const string &option) {
    return data.at(section).at(option);
}

unordered_map<string, unordered_map<string, string>> IniParse::getData() {
    return data;
}